package com.shanxi.cz.module.biz.framework.mqtt.handler;

import com.shanxi.cz.module.biz.framework.mqtt.service.MqttBusinessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class MqttMessageHandler implements MessageHandler {

    @Autowired
    private MqttBusinessService mqttBusinessService;

    @Override
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public void handleMessage(Message<?> message) throws MessagingException {
        try {
            // 打印所有消息头信息
            Map<String, Object> headers = message.getHeaders();
            log.debug("=== 收到MQTT消息头信息 ===");
            headers.forEach((key, value) -> {
                log.debug("Header - {}: {}", key, value);
            });
            log.debug("=== 消息头信息结束 ===");
            // 获取消息头信息
            String topic = (String) message.getHeaders().get("mqtt_receivedTopic");
            Integer qos = (Integer) message.getHeaders().get("mqtt_receivedQos");
            Boolean retained = (Boolean) message.getHeaders().get("mqtt_retained");
            String payload = message.getPayload().toString();

            log.info("✅ 收到MQTT消息 - Topic: {}, Qos: {}, Retained: {}, Payload长度: {}",
                    topic, qos, retained, payload.length());
            log.info("消息内容: {}", payload);

            // 异步处理业务逻辑
            mqttBusinessService.processMessage(topic, payload);

        } catch (Exception e) {
            log.error("❌ MQTT消息处理异常", e);
            throw new MessagingException("处理MQTT消息失败", e);
        }
    }
}